﻿using System;
using System.Collections.Generic;
using System.Linq;
using WebTest.Core.Entities.Interfaces;

namespace WebTest.Core.Entities.OrderAggregate
{
    public class Order : BaseEntity, IAggregate
    {
        /// <summary>
        /// 订单编号,使用Guid
        /// </summary>
        public new Guid Id { get; private set; }
        /// <summary>
        /// 会员
        /// </summary>
        public Member Member { get; private set; }
        /// <summary>
        /// 订单地址,值对象,单独数据表
        /// </summary>
        public Address OrderAddress { get; private set; }
        private readonly List<OrderItem> _items = new List<OrderItem>();
        /// <summary>
        /// 订单中的商品列表
        /// </summary>
        public IReadOnlyCollection<OrderItem> Items => _items.AsReadOnly();
        /// <summary>
        /// 订单总价
        /// </summary>
        public decimal TotalPrice
        {
            get
            {
                return _items.Sum(x => x.TotalPrice);
            }
        }

        public Order()
        {
            Id = new Guid();
        }
        public void SetMember(Member member)
        {
            Member = member ?? throw new ArgumentNullException(nameof(member));
        }
        public void SetOrderAddress(Address address)
        {
            OrderAddress = address ?? throw new ArgumentNullException(nameof(address));
        }
        public void AddOrderItem(OrderItem item)
        {
            var _item = _items.SingleOrDefault(x => x.Id == item.Id);
            if(_item != null)
            {
                _item.SetAmount(_item.Amount + 1);
            }
            else
            {
                _items.Add(item);
            }
        }
        public void RemoveOrderItem(OrderItem item)
        {
            if(!_items.Exists(x=>x.Id == item.Id))
            {
                _items.Remove(item);
            }
        }
        public void ClearOrderItem()
        {
            if (_items.Any())
            {
                _items.Clear();
            }
        }
    }
}
